package com.example.androidapp2;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.example.androidapp2.DbClasses.ItemCategoria;
import com.example.androidapp2.DbClasses.Utils;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.xyzdesa.droidnomy.R;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {	
	DbAdapter DbConect;
	private AdView adView;

	public PopUpConfigu pupConfi;
	private PopUpCategorias pupCate;
	private PopUpPorcentajes pupPorce;
	public PopUpConfirma pupConfirma;

	//PantallaPrincipal	
	private Button btnResta;
	private EditText txtIngresos;
	private EditText txtEgresos;
	private EditText txtResta;		
	private TextView lblPorcentaje;	
	private TextView lblErrores;
	private ProgressBar skTotal;
	private Spinner spnCategorias;	

	private List<Integer> ValoresAnteriores;
	private List<ItemCategoria> ListaCategorias;

	private Button btnMil;
	private Button btnQuinientos;
	private Button btnCien;
	private Button btnCincuenta;
	private Button btnDiez;
	private Button btnCinco;
	private Button btnUno;
	private ImageButton btnAtras;
	private ImageButton btnDeshacer;

	private ImageButton btnCategorias;	
	private String AdUnitId="a1502ab8f63427a";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try{
			super.onCreate(savedInstanceState);
			setContentView(R.layout.view_flipper);
			DBOpen();		
			Utils.Ctx = this;

			adView = new AdView(this, AdSize.BANNER, AdUnitId);
			LinearLayout lyt = (LinearLayout) findViewById(R.id.lytAds);
			lyt.addView(adView);

			AdRequest adRequest = new AdRequest();
			adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
			adRequest.addTestDevice("0B1F8EBB48ACFF5BFEE6F19692F21659");
			adView.loadAd(adRequest);			

			pupConfi = new PopUpConfigu(this, DbConect);
			pupCate = new PopUpCategorias(this, DbConect);
			pupPorce = new PopUpPorcentajes(this, DbConect, this);
			pupConfirma = new PopUpConfirma(this, DbConect,pupConfi);

			SetControls();
			SetControlValues();
			if( DbConect.SetUltimoIngreso())
				pupConfi.Show();

			ActualizarProgressBar();
		}catch (Exception e) 
		{
			lblErrores.setText("Error al cargar: "+e.getMessage());	
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onDestroy() {
		adView.destroy();
		super.onDestroy();
	}

	public boolean onOptionsItemSelected(MenuItem item) 
	{ 
		if(item.getItemId() == R.id.itmAgregarCat)
			pupCate.Show(true);
		else if(item.getItemId() == R.id.itmEliminarCat)
			pupCate.Show(false);
		else if(item.getItemId() == R.id.itmMensual)
			pupConfirma.show("ReestMes",null);
		else if (item.getItemId() == R.id.itmAnual)
			pupConfirma.show("ReestAnio", null);
		else if (item.getItemId() == R.id.itmTodos)
			pupConfirma.show("ReestTodos",null);
		else if(item.getItemId() == R.id.itmCorregir)
			pupConfi.show(true);
		else if(item.getItemId() == R.id.itmAyuda)
			OpenHelp();

		return true;
	}

	public void SetControls()
	{
		btnResta = (Button) findViewById(R.id.btnResta);
		txtIngresos = (EditText) findViewById(R.id.txtIngresos);
		txtEgresos =(EditText) findViewById(R.id.txtEgresos);
		txtResta = (EditText) findViewById(R.id.txtResta);			
		lblPorcentaje = (TextView) findViewById(R.id.lblPorcentaje);			 
		lblErrores = (TextView) findViewById(R.id.lblErrores);		

		skTotal = (ProgressBar) findViewById(R.id.skTotal);
		spnCategorias = (Spinner) findViewById(R.id.spnCategorias);	

		btnMil = (Button)  findViewById(R.id.btn1000);
		btnQuinientos = (Button)  findViewById(R.id.btn500);
		btnCien = (Button)  findViewById(R.id.btn100);
		btnCincuenta = (Button)  findViewById(R.id.btn50);
		btnDiez = (Button)  findViewById(R.id.btn10);
		btnCinco = (Button)  findViewById(R.id.btn5);
		btnUno = (Button)  findViewById(R.id.btn1);
		btnAtras = (ImageButton)  findViewById(R.id.btnAtras);
		btnDeshacer = (ImageButton) findViewById(R.id.btnDeshacer);
		ValoresAnteriores = new ArrayList<Integer>();	

		btnCategorias = (ImageButton) findViewById(R.id.btnCategorias);						
	}

	public void OpenHelp()
	{	
		Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + DbAdapter.DB_PATH + DbAdapter.AYUDAPATH + DbAdapter.AYUDAP));
		Intent browserIntent = new Intent(Intent.ACTION_VIEW).setData(uri);
		browserIntent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
		startActivity(browserIntent);
	}

	public void SetControlValues()
	{		
		CargarSpinnerCategorias();
		SetListenerBotones(new Button[]{btnMil,btnQuinientos,btnCien,btnCincuenta,btnDiez,btnCinco,btnUno});
	}

	public void SetListenerBotones(Button[] btns)
	{
		for (Button bt : btns) {
			bt.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					ClickSumar(((Button)v).getText().toString());
				}
			});
		}

		btnDeshacer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {				
				pupConfirma.show("Main", null);
			}
		});

		btnResta.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {				
				if(!txtResta.getText().toString().equals("")){
					GuardarMovimiento(Integer.parseInt(txtResta.getText().toString()),"Eg",Utils.GetFecha(),"EFT",ListaCategorias.get( spnCategorias.getSelectedItemPosition()).Codigo);
					ActualizarProgressBar();
					txtResta.setText("");
					ValoresAnteriores = new ArrayList<Integer>();
				}
			}
		});

		btnCategorias.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				try{									
					pupPorce.CargarPantallaPorcentajes();
					pupPorce.show();
				}catch(Exception e)
				{
					lblErrores.setText(e.getMessage());					
				}
			}
		});

		btnAtras.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(ValoresAnteriores.size()>0 && !ValoresAnteriores.get(ValoresAnteriores.size()-1).equals(0))
				{
					txtResta.setText(String.valueOf(ValoresAnteriores.get(ValoresAnteriores.size()-1)));
					ValoresAnteriores.remove(ValoresAnteriores.size()-1);
				}
				else
					txtResta.setText("");
			}
		});			
	}

	public void CargarSpinnerCategorias()
	{		 
		ListaCategorias = DbConect.GetCategorias("spnCategorias",true,false);
		List<String> lsCat = new ArrayList<String>();
		for (ItemCategoria it : ListaCategorias) {
			lsCat.add(it.Descripcion);
		}

		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lsCat);
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);		
		spnCategorias.setAdapter(spinnerAdapter);	
	}

	public void ClickSumar(String txt)
	{		

		int total=0;
		if(txtResta.getText().toString().length()>0)
			total = Integer.parseInt(txtResta.getText().toString());
		ValoresAnteriores.add(total);
		total += Integer.parseInt(txt.substring(1));
		txtResta.setText(String.valueOf( total));
	}

	public void GuardarMovimiento(int txt, String tipo, String fecha, String medio, int categoria) {
		try {
			DbConect.InsertMovimiento(txt, tipo, fecha,medio,categoria);
		}catch (Exception e) {
			lblErrores.setText("Error al cargar: "+e.getMessage());
		}
	}

	public void ActualizarProgressBar()
	{			
		int ingreso = DbConect.GetTotalMovimientosMes("In", Utils.GetMesAnio());
		int egreso = DbConect.GetTotalMovimientosMes("Eg",Utils.GetMesAnio());

		txtIngresos.setText("$"+String.valueOf(ingreso));
		txtEgresos.setText("$"+String.valueOf(egreso));

		double porcentaje = (ingreso>0)?100-((egreso * 100)/ingreso):0;
		long pesos = ingreso-egreso;			

		lblPorcentaje.setText("$"+String.valueOf(pesos) +" ~ "+String.valueOf(porcentaje) + "%");

		skTotal.setMax(100);
		skTotal.setProgress((int) porcentaje);

		skTotal.setEnabled(false);
	}

	public void DBOpen(){
		Resources r = getResources();
		try 
		{
			DbConect= new DbAdapter(this,r);
			DbConect.createDataBase();	
			DbConect.openDataBase();
			DbConect.CopiarAyuda();
		} catch (IOException e) {
			lblErrores.setText(e.getMessage());
		}
	}
}